package org.holynite.fieldmanage.managed.controller

import org.holynite.fieldmanage.ejbs.ChargeManagement
import org.holynite.fieldmanage.entities.ChargeRule
import org.holynite.fieldmanage.managed.model.ChargeRuleFormBean
import org.holynite.fieldmanage.managed.model.ChargeRulesBean
import org.holynite.fieldmanage.managed.model.ChargeSchemeFormBean
import org.holynite.fieldmanage.managed.model.ChargeSchemesBean
import org.holynite.fieldmanage.utils.LocaleString

import javax.ejb.EJB
import javax.faces.bean.ManagedBean
import javax.faces.bean.ManagedProperty
import javax.faces.bean.ViewScoped
import javax.faces.model.SelectItem
import javax.inject.Inject

/**
 * Created by midnite on 15/2/1.
 */
@ManagedBean
@ViewScoped
class ChargeRuleBean implements Serializable {

    @EJB(beanName = "chargeControl")
    ChargeManagement chargeService
    @ManagedProperty("#{chargeSchemeFormBean}")
    ChargeSchemeFormBean csForm
    @ManagedProperty("#{chargeRuleFormBean}")
    ChargeRuleFormBean crForm
    @ManagedProperty("#{chargeRulesBean}")
    ChargeRulesBean crBean
    @ManagedProperty("#{chargeSchemesBean}")
    ChargeSchemesBean csBean
    @Inject
    LocaleString locale

    def searchRules() {
        crBean.loadRulesInScheme(csForm.selectedScheme, crForm.searchKeyword)
        null
    }

    def saveRule() {
        def beginCal = Calendar.instance
        def endCal = Calendar.instance
        beginCal.set(Calendar.HOUR_OF_DAY, crForm.beginHour)
        beginCal.set(Calendar.MINUTE, crForm.beginMinute)
        endCal.set(Calendar.HOUR_OF_DAY, crForm.endHour)
        endCal.set(Calendar.MINUTE, crForm.endMinute)

        if (crForm.addMode) {
            ChargeRule newRule = new ChargeRule(
                    name: crForm.ruleName, price: crForm.price,
                    begin: beginCal.getTime(), end: endCal.getTime()
            )
            def selectedChargeScheme = csBean.findScheme(csForm.selectedScheme)
            chargeService.addRule(selectedChargeScheme, newRule)
        } else {
            def selectedChargeScheme = csBean.findScheme(csForm.selectedScheme)
            selectedChargeScheme = chargeService.fillScheme(selectedChargeScheme)
            def selectedChargeRule = selectedChargeScheme.chargeRules.find { it.ruleId.equals(crForm.selectedRule) }
            selectedChargeRule.name = crForm.ruleName
            selectedChargeRule.begin = beginCal.getTime()
            selectedChargeRule.end = endCal.getTime()
            selectedChargeRule.price = crForm.price
            chargeService.saveRule(selectedChargeRule)
        }
        crForm.clearForm()
        crBean.loadRulesInScheme(csForm.selectedScheme, crForm.searchKeyword)
        null
    }

    def removeRule() {
        chargeService.removeRule(csForm.selectedScheme, crForm.selectedRule)
        crForm.clearForm()
        crBean.loadRulesInScheme(csForm.selectedScheme, crForm.searchKeyword)
        null
    }
}
